package com.rmiad.config;

import lombok.extern.slf4j.Slf4j;
import org.noear.solon.annotation.Component;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.Handler;
import org.noear.solon.core.handle.Result;
import org.noear.solon.core.route.RouterInterceptor;
import org.noear.solon.core.route.RouterInterceptorChain;

/**
 * @author wyl
 * @date 2025年05月02日 上午8:58
 */
@Slf4j
@Component
public class GlobalInterceptor implements RouterInterceptor {

    @Override
    public void doIntercept(Context ctx, Handler mainHandler, RouterInterceptorChain chain) throws Throwable {
        chain.doIntercept(ctx, mainHandler);
    }

    @Override
    public Object postResult(Context ctx, Object result) throws Throwable {
        //提示：此处只适合做结果类型转换
        if (result != null && !(result instanceof Throwable) && ctx.action() != null) {
            if (result instanceof Result) {
                int code = ((Result<?>) result).getCode();
                int status;
                if (code == 200) {
                    status = 0;
                } else if (code == 400) {
                    status = 1;
                } else {
                    status = code;
                }
                return new com.rmiad.controller.Result<>(status,
                        ((Result<?>) result).getDescription(), ((Result<?>) result).getData());
            }
        }
        if (result instanceof Throwable) {
            log.error(((Throwable) result).getMessage(), (Throwable) result);
            return new com.rmiad.controller.Result<>(-1,
                    ((Throwable) result).getMessage(), null);
        }
        return result;
    }

}
